<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入品牌名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="显示状态" prop="showStatus">
        <el-select v-model="queryParams.showStatus" placeholder="请选择显示状态" clearable size="small">
          <el-option
            v-for="dict in showStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:brand:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mall:brand:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mall:brand:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['mall:brand:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="品牌id" align="center" prop="brandId" v-if="false"/>
      <el-table-column label="品牌名" align="center" prop="name"/>
      <el-table-column prop="logo" label="品牌logo">
        <template slot-scope="{row}">
          <el-image
            style="width: 50px; height: 50px"
            :src="row.logo"
            fit="fill"
            :preview-src-list="[row.logo]"
          />
        </template>
      </el-table-column>
      <el-table-column label="介绍" align="center" prop="descript"/>
      <el-table-column label="显示状态" align="center" prop="showStatus" :formatter="showStatusFormat"/>
      <el-table-column label="检索首字母" align="center" prop="firstLetter"/>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:brand:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-postcard"
            @click="handleRelate(scope.row)"
          >关联分类
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mall:brand:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改品牌对话框 -->
    <el-dialog :title="title" v-if="open" :close-on-click-modal="false" :visible.sync="open" width="600px"
               append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="品牌名" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名"/>
        </el-form-item>
        <el-form-item label="品牌logo地址">
          <imageUpload :maxCount="1" v-model="form.logo"/>
        </el-form-item>
        <el-form-item label="介绍" prop="descript">
          <el-input v-model="form.descript" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="显示状态">
          <el-radio-group v-model="form.showStatus">
            <el-radio
              v-for="dict in showStatusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="检索首字母" prop="firstLetter">
          <el-input v-model="form.firstLetter" placeholder="请输入检索首字母"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 关联分类弹出层 -->
    <el-dialog class="pub_dialog" title="关联列表" v-if="openRelate" :close-on-click-modal="false" :visible.sync="openRelate" width="800px"
               append-to-body>
      <el-form :model="relateQueryParams" ref="relateQueryForm" :inline="true" label-width="68px">
        <el-form-item label="分类名" prop="name">
          <el-input
            v-model="relateQueryParams.catalogName"
            placeholder="请输入分类名"
            clearable
            size="mini"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleRelateQuery">搜索</el-button>
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multipleRelate" @click="handleRelateDelete">删除</el-button>
          <el-popover
            style="padding: 0 10px"
            placement="top"
            v-model="openChooseRelate"
            width="500">
            <el-cascader
              style="width: 400px"
              filterable
              clearable
              v-model="categoryValue"
              :props="props"
              :options="categoryOptions"
              @change="handleChange"></el-cascader>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="openChooseRelate = false">取消</el-button>
              <el-button type="primary" size="mini" @click="saveRelate">确定</el-button>
            </div>
            <el-button size="mini" type="primary" plain icon="el-icon-plus" slot="reference">关联分类</el-button>
          </el-popover>
        </el-form-item>
      </el-form>
      <el-table v-loading="relateLoading" max-height="300px" @selection-change="handleRelateSelectionChange" :data="brandRelateList">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="品牌名" align="center" prop="brandName" />
        <el-table-column label="分类名" align="center" prop="catalogName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleRelateDelete(scope.row)"
            >移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="totalRelate>0"
        :total="totalRelate"
        :page.sync="relateQueryParams.pageNum"
        :limit.sync="relateQueryParams.pageSize"
        @pagination="getRelateList"
      />
    </el-dialog>

  </div>
</template>

<script>
  import {listBrand, getBrand, delBrand, addBrand, updateBrand, exportBrand} from "@/api/mall/pms/brand";
  import {listCategoryBrand, delCategoryBrand, addCategoryBrand, exportCategoryBrand} from "@/api/mall/pms/categoryBrand";
  import ImageUpload from '@/components/ImageUpload';
  import { listCategory} from "@/api/mall/pms/category";


  export default {
    name: "Brand",
    components: {
      ImageUpload,
    },
    data() {
      return {
        categoryValue:undefined,
        //分类id
        catalogId:undefined,
        //品牌id
        brandId:undefined,
        //级联选择器
        props: {
          value: 'id',
          label: 'name',
          children: 'children'
        },
        //分类数据
        categoryOptions:[],
        //按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 遮罩层
        relateLoading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        singleRelate: true,
        // 非多个禁用
        multiple: true,
        multipleRelate: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 关联总条数
        totalRelate: 0,
        // 品牌表格数据
        brandList: [],
        // 品牌关联表格数据
        brandRelateList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层
        openRelate: false,
        // 是否显示弹出层
        openChooseRelate: false,
        // 显示状态字典
        showStatusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          descript: undefined,
          showStatus: undefined,
        },
        // 查询参数
        relateQueryParams: {
          pageNum: 1,
          pageSize: 10,
          brandId:undefined,
          catalogName:undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            {required: true, message: "品牌名不能为空", trigger: "blur"}
          ],
        }
      };
    },
    created() {
      this.getList();
      this.buildTree();
      this.getDicts("mall_nav_status").then(response => {
        this.showStatusOptions = response.data;
      });
    },
    methods: {
      //选择关联的分类
      handleChange(data){
        this.catalogId=data[data.length-1];
      },
      //保存关联分类
      saveRelate(){
        let params={
          brandId:this.brandId,
          catalogId:this.catalogId,
        }
        addCategoryBrand(params).then(response => {
          this.getRelateList();
          this.openChooseRelate=false;
          this.categoryValue=''
        }).catch(() => {
        });

        this.openChooseRelate=false;
      },
      //级联选择器
      buildTree(){
        this.categoryOptions = [];
        listCategory().then(response => {
          this.categoryOptions = this.handleTree(response.data, "id", "parentId");
        })
      },
      /** 查询品牌列表 */
      getList() {
        this.loading = true;
        listBrand(this.queryParams).then(response => {
          this.brandList = response.rows;
          this.total = response.total;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      },
      /** 查询品牌关联列表 */
      getRelateList() {
        this.relateLoading = true;
        listCategoryBrand(this.relateQueryParams).then(response => {
          this.brandRelateList = response.rows;
          this.totalRelate = response.total;
          this.relateLoading = false;
        }).catch(() => {
          this.relateLoading = false;
        });
      },

      // 显示状态字典翻译
      showStatusFormat(row, column) {
        return this.selectDictLabel(this.showStatusOptions, row.showStatus);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          brandId: undefined,
          name: undefined,
          logo: undefined,
          descript: undefined,
          showStatus: 0,
          firstLetter: undefined,
          sort: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 搜索按钮操作 */
      handleRelateQuery() {
        this.relateQueryParams.pageNum = 1;
        this.getRelateList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.brandId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      // 多选框选中数据
      handleRelateSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.singleRelate = selection.length !== 1
        this.multipleRelate = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.form.showStatus = 1;
        this.open = true;
        this.title = "添加品牌";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const brandId = row.brandId || this.ids
        getBrand(brandId).then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "修改品牌";
        }).catch(() => {
          this.loading = false;
        });
      },
      /**关联操作按钮**/
      handleRelate(row){
         this.openRelate=true;
         this.brandId=row.brandId;
         this.relateQueryParams.brandId=row.brandId;
         this.getRelateList();
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.brandId != null) {
              updateBrand(this.form).then(response => {
                this.buttonLoading = false;
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch(() => {
                this.buttonLoading = false;
              });
            } else {
              addBrand(this.form).then(response => {
                this.buttonLoading = false;
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const brandIds = row.brandId || this.ids;
        this.$confirm('是否确认删除品牌编号为"' + brandIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delBrand(brandIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {
          this.loading = false;
        });
      },
      /**移除关联关系**/
      handleRelateDelete(row){
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除品牌分类关联编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delCategoryBrand(ids);
        }).then(() => {
          this.loading = false;
          this.getRelateList();
          this.msgSuccess("删除成功");
        }).catch(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有品牌数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportBrand(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {
          this.exportLoading = false;
        });
      }
    }
  };
</script>
<style scoped>
  .el-dialog__wrapper /deep/ .el-dialog__body {
    padding-top: 10px !important;
    padding-bottom: 5px !important;
  }
  .self_dialog /deep/ .el-dialog {
    height: 30%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    padding-left: 15px;
  }
  .self_dialog /deep/ .el-dialog .el-dialog__body {
    padding-top: 5px !important;
    overflow: hidden;
    overflow-y: auto;
  }
  .self_dialog /deep/ .el-dialog .el-dialog__footer {
    left: 80%;
    bottom: 0;
    position: absolute;
  }


  .pub_dialog {
    display: flex;
    justify-content: center;
    align-items: Center;
  }
  .pub_dialog /deep/ .el-dialog {
    margin: 0 auto !important;
    height: 70%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    padding-left: 15px;
  }
  .pub_dialog /deep/ .el-dialog .el-dialog__body {
    padding-top: 5px !important;
    overflow: hidden;
    margin-bottom: 40px;
  }
  .pub_dialog /deep/ .el-dialog .el-dialog__footer {
    left: 80%;
    bottom: 0;
    position: absolute;
  }
</style>
